<?php

// +--------------------------------------------
// | Name: 星空后台 系统管理
// +--------------------------------------------
// | Version: V5.0
// +--------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sian.cn>
// +--------------------------------------------
// | Time: 2021-04-08 09:47
// +--------------------------------------------
declare(strict_types=1);

namespace app\xingkong\controller\v1;

use app\common\common\BackendController;
use app\common\model\Cate as CateModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Menu as MenuModel;
use app\common\model\Store as StoreModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Area as AreaModel;
use app\common\model\BonusRule as BonusRuleModel;
use app\common\model\RefundReason as RefundReasonModel;
use app\common\services\AreaServices;
use app\common\model\ShippingTemplate as ShippingTemplateModel;
use app\common\model\PushMsg as PushMsgModel;
use think\facade\Db;
use think\facade\View;

/**
 * @xk 系统管理
 */
class System extends BackendController
{
    // +-----------------------
    // | 系统管理，基础信息设置
    // +------------------------

    /**
     * @xk 基础信息管理
     *
     * @method config
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T10:28:55+080
     */
    public function config(ConfigModel $configModel)
    {
        $system_config_site = Config('system_config.system_site');
        $list = [];
        if ($system_config_site) {
            foreach ($system_config_site as $key => $value) {
                $list[$key]['value'] = $value;
                $list[$key]['list'] = $configModel
                      ->where([['site_id', '=', $key]])
                      ->field('*,content as show_content')
                      ->withAttr('show_content', function ($value, $data) {
                          if ($data['type_id'] == 2) {
                              return getShowUrl($value);
                          } else {
                              return $value;
                          }
                      })
                      ->order('type_id asc')
                      ->select()
                      ->toArray();
            }
        }
        return View::fetch('', ['system_config_site' => $system_config_site, 'list' => $list]);
    }

    /**
     * @xk 系统配置更新
     *
     * @method configSave
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T11:31:06+080
     */
    public function configSave(ConfigModel $configModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = '';
        try {
            $param = request()->param();
            $key_arr = isset($param['value']) ? $param['value'] : '';
            if ($key_arr) {
                foreach ($key_arr as $key => $value) {
                    $configModel->find($key)->save(['content' => $value]);
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 系统变量列表
     *
     * @method configList
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T10:29:24+080
     */
    public function configList(ConfigModel $configModel)
    {
        $param = request()->param();
        $site_id = isset($param['site_id']) ? $param['site_id'] : 0;
        if (request()->isAjax()) {
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $page = isset($param['page']) ? (int) $param['page'] : 0;
            $limit = isset($param['limit']) ? (int) $param['limit'] : 15;
            $condition = [];
            if ($site_id > 0) {
                $condition[] = ['c.site_id', '=', $site_id]; //写入站点信息
            }
            if ($keywords) {
                $condition[] = ['c.sign|c.name|c.content', 'like', '%'.$keywords.'%'];
            }
            $list = $configModel
                    ->alias('c')
                    ->where($condition)
                    ->field('c.`config_id`,c.`site_id`,c.`name`,c.`sign`,c.`type_id`,c.`status`,c.`update_time`')
                    ->withAttr('site_id', function ($value, $data) {
                        $system_site = config('system_config.system_site');

                        return $system_site[$value];
                    })
                    ->withAttr('type_id', function ($value, $data) {
                        $system_type = config('system_config.system_type');

                        return $system_type[$value];
                    })
                    ->page($page, $limit)
                    ->select()
                    ->toArray();
            $count = $configModel
                     ->alias('c')
                     ->where($condition)
                     ->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $count;
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }

        return View::fetch('', ['site_id' => $site_id]);
    }

    /**
     * @xk 系统变量添加
     *
     * @method configListCreate
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T11:32:30+080
     */
    public function configListCreate()
    {
        $param = request()->param();
        $site_id = isset($param['site_id']) ? $param['site_id'] : 0;
        $system_site = config('system_config.system_site');
        $system_type = config('system_config.system_type');

        return View::fetch('', ['site_id' => $site_id, 'system_site' => $system_site, 'system_type' => $system_type]);
    }

    /**
     * @xk 系统变量编辑
     *
     * @method configListEdit
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T11:34:27+080
     */
    public function configListEdit(ConfigModel $configModel)
    {
        $param = request()->param();
        $config_id = isset($param['config_id']) ? $param['config_id'] : 0;
        if ($config_id <= 0) {
            $this->error('请选择需要编辑的系统变量');
        }
        $info = $configModel->find($config_id);
        $system_site = config('system_config.system_site');
        $system_type = config('system_config.system_type');

        return View::fetch('', ['info' => $info, 'system_site' => $system_site, 'system_type' => $system_type]);
    }

    /**
     * @xk 系统变量添加
     *
     * @method configListSave
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T13:03:34+080
     */
    public function configListSave(ConfigModel $configModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $check_result = $configModel->validate($param, $act);
            switch ($act) {
                case 'create':
                    $res = $configModel->create($param);
                    break;
                case 'edit':
                    $res = $configModel->find($param['config_id'])->save($param);
                    break;
            }
            $result_code = 200;
            $result_msg = '处理成功';
            $resultData = '';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404; //访问出错
            $result_msg = $e->getMessage();
            $resultData = '';
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 系统配置动态更新
     *
     * @method configChanageValue
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T13:11:01+080
     */
    public function configChanageValue(ConfigModel $configModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                $result_code = 404;
                $result_msg = '请选择需要修改的数据';
                $this->result($code, $msg, $result_code, $result_msg);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $configModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 系统变量软删除
     *
     * @method configDestroy
     *
     * @param ConfigModel $configModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T13:18:33+080
     */
    public function configDestroy(ConfigModel $configModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
              throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $configModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // +------------------------
    // | 后台菜单管理
    // +------------------------

    /**
     * @xk 菜单列表
     *
     * @method menu
     *
     * @param MenuModel $menuModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T13:41:59+080
     */
    public function menu(MenuModel $menuModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $condition = [];
            if ('' != $keywords) {
                $condition[] = ['m.menu_name|m.content', 'like', '%'.$keywords.'%'];
            }
            $list = $menuModel
                    ->alias('m')
                    ->where($condition)
                    ->field('m.menu_id,m.menu_name,m.parent_id,m.status,m.linkurl,m.update_time,m.icon,m.sign,m.order_id')
                    ->order('order_id asc')
                    ->select()
                    ->toArray();
            $count = $menuModel
                     ->alias('m')
                     ->where($condition)
                     ->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $this->result($code, $msg, $result_code, $result_msg, $list, $count);
        }

        return View::fetch();
    }

    /**
     * @xk 菜单添加
     *
     * @method menuAdd
     *
     * @param MenuModel $menuModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T14:42:18+080
     */
    public function menuCreate(MenuModel $menuModel)
    {
        $param = request()->param();
        $parent_id = isset($param['parent_id']) ? $param['parent_id'] : 0;
        $menu_list = $menuModel->getTreeList('menu_id'); // 获取栏目树形列表
        return View::fetch('', ['menu_list' => $menu_list, 'parent_id' => $parent_id]);
    }

    /**
     * @xk 菜单编辑
     *
     * @method menuEdit
     *
     * @param MenuModel $menuModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T14:45:23+080
     */
    public function menuEdit(MenuModel $menuModel)
    {
        $param = request()->param();
        $menu_id = isset($param['menu_id']) ? $param['menu_id'] : 0;
        if ($menu_id <= 0) {
            $this->error('请选择需要编辑的菜单');
        }
        $info = $menuModel->find($menu_id);
        $menu_list = $menuModel->getTreeList('menu_id');

        return View::fetch('', ['info' => $info, 'menu_list' => $menu_list]);
    }

    /**
     * @xk 菜单保存
     *
     * @method menuSave
     *
     * @param MenuModel $menuModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T14:45:55+080
     */
    public function menuSave(MenuModel $menuModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            // 验证器规则验证 通过baseModel进行公共处理
            $check_result = $menuModel->validate($param, $act);
            switch ($act) {
                case 'create':
                    $res = $menuModel->create($param);
                    break;
                case 'edit':
                    $res = $menuModel->find($param['menu_id'])->save($param);
                    break;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 菜单数据动态修改
     *
     * @method menuChanageValue
     *
     * @param MenuModel $menuModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T15:04:14+080
     */
    public function menuChanageValue(MenuModel $menuModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要修改的数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $menuModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 菜单删除
     *
     * @method menuDestroy
     *
     * @param MenuModel $menuModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T15:05:44+080
     */
    public function menuDestroy(MenuModel $menuModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                $result_code = 404;
                $result_msg = '请选择需要删除的数据';
                $this->result($code, $msg, $result_code, $result_msg);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $menuModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // **********************
    // | 仓库以及运费管理
    // **********************
    /**
     * @xk 仓库管理
     *
     * @method store
     * @param  StoreModel $storeModel                [description]
     * @return [type]     [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function store(StoreModel $storeModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page'])?(int)$param['page']:1;
            $limit = isset($param['limit'])?(int)$param['limit']:30;
            $keywords = isset($param['keywords'])?$param['keywords']:'';
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['store_name','like','%'.$keywords.'%'];
            }
            $resultData = [];
            $resultData['list'] = $storeModel
                              ->where($condition)
                              ->field('`store_id`,`store_name`,`store_logo`,`status`,`order_id`,`update_time`')
                              ->order(['order_id desc','create_time desc'])
                              ->page($page, $limit)
                              ->select()
                              ->toArray();
            $resultData['count'] = $storeModel->where($condition)->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch();
    }
    /**
     * @xk 仓库创建
     *
     * @method storeCreate
     * @return [type]      [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe    <zhonghuaxinxing@sina.cn>
     */
    public function storeCreate()
    {
        return View::fetch();
    }
    /**
     * @xk 仓库编辑
     *
     * @method storeEdit
     * @param  StoreModel $storeModel                [description]
     * @return [type]     [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function storeEdit(StoreModel $storeModel)
    {
        $param = request()->param();
        $store_id = isset($param['store_id'])?$param['store_id']:0;
        $info = $storeModel->find($store_id);
        return View::fetch('', ['info'=>$info?$info->toArray():[]]);
    }
    /**
     * @xk 仓库保存
     *
     * @method storeSave
     * @param  StoreModel $storeModel                [description]
     * @return [type]     [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function storeSave(StoreModel $storeModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            // 验证器规则验证 通过baseModel进行公共处理
            $check_result = $storeModel->validate($param, $act);
            switch ($act) {
              case 'create':
                  $res = $storeModel->create($param);
                  break;
              case 'edit':
                  $res = $storeModel->find($param['store_id'])->save($param);
                  break;
          }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 仓库信息调整
     *
     * @method storeChanageValue
     * @param  StoreModel        $storeModel                [description]
     * @return [type]            [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function storeChanageValue(StoreModel $storeModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要修改或调整的数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $storeModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 仓库删除
     *
     * @method storeDestroy
     * @param  StoreModel   $storeModel                [description]
     * @param  GoodsModel   $goodsModel                [description]
     * @return [type]       [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe     <zhonghuaxinxing@sina.cn>
     */
    public function storeDestroy(StoreModel $storeModel, GoodsModel $goodsModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的仓库", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $goods_count = $goodsModel->where([['store_id','=',$value]])->count();
                if ($goods_count > 0) {
                    $j++;
                    continue;
                }
                $res = $storeModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
            if ($j > 0) {
                $result_msg = ',其中存在'.$j.'个仓库因为存在关联产品无法进行处理';
            }
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // ********************
    // | 运费模板管理
    // *********************
    /**
     * @xk 运费模板添加
     *
     * @method shippingTemplate
     * @param  ShippingTemplateModel $shippingTemplateModel     [description]
     * @return [type]                [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function shippingTemplate(ShippingTemplateModel $shippingTemplateModel)
    {
        $param = request()->param();
        $store_id = isset($param['store_id'])?$param['store_id']:0;
        if (request()->isAjax()) {
            $page = isset($param['page'])?(int)$param['page']:1;
            $limit = isset($param['limit'])?(int)$param['limit']:30;
            $keywords = isset($param['keywords'])?$param['keywords']:'';
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['area_show','like','%'.$keywords.'%'];
            }
            $condition[] = ['store_id','=',$store_id];
            $resultData = [];
            $resultData['list'] = $shippingTemplateModel
                              ->where($condition)
                              ->withAttr('price_type', function ($value, $data) {
                                  return $value==1?'每件计算':'整单计算';
                              })
                              ->page($page, $limit)
                              ->select()
                              ->toArray();
            $resultData['count'] = $shippingTemplateModel->where($condition)->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch('', ['store_id'=>$store_id]);
    }
    /**
     * @xk 运费模板添加
     *
     * @method shippingTemplateCreate
     * @return [type]                 [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe               <zhonghuaxinxing@sina.cn>
     */
    public function shippingTemplateCreate()
    {
        $param = request()->param();
        $store_id = isset($param['store_id'])?$param['store_id']:0;
        return View::fetch('', ['store_id'=>$store_id]);
    }
    /**
     * @xk 运费编辑
     *
     * @method shippingTemplateEdit
     * @param  ShippingTemplateModel $shippingTemplateModel     [description]
     * @return [type]                [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function shippingTemplateEdit(ShippingTemplateModel $shippingTemplateModel)
    {
        $param = request()->param();
        $shipping_type_id = isset($param['shipping_type_id'])?$param['shipping_type_id']:0;
        $info = $shippingTemplateModel->find($shipping_type_id);
        return View::fetch('', ['info'=>$info]);
    }
    /**
     * @xk 运费模板保存
     *
     * @method shippingTemplateSave
     * @param  ShippingTemplateModel $shippingTemplateModel     [description]
     * @return [type]                [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function shippingTemplateSave(ShippingTemplateModel $shippingTemplateModel, AreaModel $areaModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $area_code = isset($param['area_code'])?$param['area_code']:'';
            $param['area_code'] = $area_code;
            $area_show = $areaModel->where([['code','in',$area_code]])->column('name');
            $param['area_show'] = implode(',', $area_show);
            // unset($param['choose_city']);
            // dump($param); die();
            // 验证器规则验证 通过baseModel进行公共处理
            $check_result = $shippingTemplateModel->validate($param, $act);
            switch ($act) {
                case 'create':
                    $res = $shippingTemplateModel->create($param);
                    break;
                case 'edit':
                    $res = $shippingTemplateModel->find($param['shipping_type_id'])->save($param);
                    break;
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 运费模板删除
     *
     * @method shippingTemplateDestroy
     * @param  ShippingTemplateModel   $shippingTemplateModel     [description]
     * @return [type]                  [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     */
    public function shippingTemplateDestroy(ShippingTemplateModel $shippingTemplateModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的运费模板", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $shippingTemplateModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // +-------------------------
    // | 地区管理
    // +----------------------------
    /**
     * @xk 地区列表
     *
     * @method area
     *
     * @param AreaModel $areaModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T16:58:13+080
     */
    public function area(AreaModel $areaModel)
    {
        $param = request()->param();
        $p_code = isset($param['p_code']) ? $param['p_code'] : 100000;
        if (request()->isAjax()) {
            $condition = [];
            $condition[] = ['area.p_code', '=', $p_code];
            $list = $areaModel
                      ->alias('area')
                      ->where($condition)
                      ->field('area.*')
                      ->withAttr('level', function ($value, $data) {
                          return 'province' == $value ? '省/直辖市' : ('city' == $value ? '城市' : ('district' == $value ? '区/县' : '乡镇/街道'));
                      })
                      ->select();
            $count = $areaModel->alias('area')->where($condition)->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $count;
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }

        return View::fetch('', ['p_code' => $p_code]);
    }

    /**
     * @xk 请求获取地址
     *
     * @method getArea
     *
     * @param AreaModel $areaModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-20T13:10:35+080
     */
    public function getArea(AreaModel $areaModel)
    {
        $param = request()->param();
        $p_code = isset($param['p_code']) ? $param['p_code'] : 100000;
        $condition = [];
        $condition[] = ['area.p_code', '=', $p_code];
        $list = $areaModel
                ->alias('area')
                ->where($condition)
                ->field('area.*')
                ->select();
        $count = $areaModel->alias('area')->where($condition)->count();
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '加载成功';
        $this->result($code, $msg, $result_code, $result_msg, $list, $count);
    }
    /**
     * @xk 更新省市区
     *
     * @method areaUpdate
     *
     * @param AreaModel    $areaModel    [description]
     * @param AreaServices $areaServices [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:04:04+080
     */
    public function areaUpdate(AreaServices $areaServices)
    {
        clearResetDb('area');
        $res = $areaServices->doUpdate();
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '更新成功';
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // ********************
    // | 分红规则管理
    // ***********************
    /**
     * @xk 分红规则列表
     *
     * @method bonusRule
     * @param  BonusRuleModel $bonusRuleModel            [description]
     * @return [type]         [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function bonusRule(BonusRuleModel $bonusRuleModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page'])?(int)$param['page']:1;
            $limit = isset($param['limit'])?(int)$param['limit']:30;
            $condition = [];
            $resultData = [];
            $resultData['list'] = $bonusRuleModel
                              ->where($condition)
                              ->page($page, $limit)
                              ->select()
                              ->toArray();
            $resultData['count'] = $bonusRuleModel->where($condition)->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch();
    }
    /**
     * @xk 分红规则创建
     *
     * @method bonusRuleCreate
     * @return [type]          [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function bonusRuleCreate()
    {
        return View::fetch();
    }
    /**
     * @xk 分红规则编辑
     *
     * @method bonusRuleEdit
     * @param  BonusRuleModel $bonusRuleModel            [description]
     * @return [type]         [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function bonusRuleEdit(BonusRuleModel $bonusRuleModel)
    {
        $param = request()->param();
        $bonus_rule_id = isset($param['bonus_rule_id'])?$param['bonus_rule_id']:0;
        $info = $bonusRuleModel->find($bonus_rule_id);
        return View::fetch('', ['info'=>$info?$info->toArray():[]]);
    }
    /**
     * @xk 分红规则保存
     *
     * @method bonusRuleSave
     * @param  BonusRuleModel $bonusRuleModel            [description]
     * @return [type]         [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function bonusRuleSave(BonusRuleModel $bonusRuleModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            // 验证器规则验证 通过baseModel进行公共处理
            $check_result = $bonusRuleModel->validate($param, $act);
            switch ($act) {
                case 'create':
                    $res = $bonusRuleModel->create($param);
                    break;
                case 'edit':
                    $res = $bonusRuleModel->find($param['bonus_rule_id'])->save($param);
                    break;
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 分红规则动态修改
     *
     * @method bonusChanageValue
     * @param  BonusRuleModel    $bonusRuleModel            [description]
     * @return [type]            [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function bonusChanageValue(BonusRuleModel $bonusRuleModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要修改的分红规则", 1);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $bonusRuleModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 分红规则删除
     *
     * @method bonusDestroy
     * @param  BonusRuleModel $bonusRuleModel            [description]
     * @return [type]         [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function bonusDestroy(BonusRuleModel $bonusRuleModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的分红规则", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $bonusRuleModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // ***************
    // | 售后原因
    // *****************
    /**
     * @xk 售后原因列表
     *
     * @method refundReason
     * @param  RefundReasonModel $refundReasonModel         [description]
     * @return [type]            [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function refundReason(RefundReasonModel $refundReasonModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $keywords = isset($param['keywords'])?$param['keywords']:'';
            $condition = [];
            if($keywords != ''){
              $condition[] = ['content','like','%'.$keywords.'%'];
            }
            $resultData = [];
            $resultData['list'] = $refundReasonModel->where($condition)->select()->toArray();
            $resultData['count'] = count($resultData['list']);
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch();
    }
    /**
     * @xk 售后原因添加
     *
     * @method refundReasonCreate
     * @return [type]             [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe           <zhonghuaxinxing@sina.cn>
     */
    public function refundReasonCreate()
    {
        return View::fetch();
    }
    /**
     * @xk 售后原因编辑
     *
     * @method refundReason
     * @param  RefundReasonModel $refundReasonModel         [description]
     * @return [type]            [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function refundReasonEdit(RefundReasonModel $refundReasonModel)
    {
        $param = request()->param();
        $refund_reason_id = isset($param['refund_reason_id'])?$param['refund_reason_id']:0;
        $info = $refundReasonModel->find($refund_reason_id);
        return View::fetch('', ['info'=>$info]);
    }
    /**
     * @xk 售后原因保存
     *
     * @method refundReasonSave
     * @param  RefundReasonModel $refundReasonModel         [description]
     * @return [type]            [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function refundReasonSave(RefundReasonModel $refundReasonModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $act = isset($param['act'])?$param['act']:'create';
            $content = isset($param['content'])?$param['content']:'';
            if ($content == '') {
                throw new \think\Exception("请输入退款原因", 404);
            }
            switch ($act) {
            case 'create':
              $res = $refundReasonModel->create($param);
              break;
            case 'edit':
              $res = $refundReasonModel->find($param['refund_reason_id'])->save($param);
              break;
          }
            Db::commit();
            $result_code = 200;
            $result_msg = '更新成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 售后原因动态修改
     *
     * @method refundReasonChanageValue
     * @param  RefundReasonModel        $refundReasonModel         [description]
     * @return [type]                   [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe                 <zhonghuaxinxing@sina.cn>
     */
    public function refundReasonChanageValue(RefundReasonModel $refundReasonModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要修改的分红规则", 1);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $refundReasonModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 售后原因删除
     *
     * @method refundReasonDestroy
     * @param  RefundReasonModel   $refundReasonModel         [description]
     * @return [type]              [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe            <zhonghuaxinxing@sina.cn>
     */
    public function refundReasonDestroy(RefundReasonModel $refundReasonModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的售后原因", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $refundReasonModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 获取城市
     *
     * @method getCity
     * @param  AreaModel  $areaModel                 [description]
     * @param  StoreModel $storeModel                [description]
     * @return [type]     [description]
     * @Time   2021-10-18
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function getCity(AreaModel $areaModel, ShippingTemplateModel $shippingTemplateModel)
    {
        $param = request()->param();
        $store_id = isset($param['store_id'])?$param['store_id']:0;
        $shipping_type_id = isset($param['shipping_type_id'])?$param['shipping_type_id']:0;
        $city_list = $areaModel
                    ->where([['level', '=', 'province']])
                    ->field('`name`,`code` as value')
                    ->select()
                    ->toArray();
        if ($city_list) {
            foreach ($city_list as $key => $value) {
                $count = 0;
                $condition = [];
                $condition1 = [];
                $condition[] = ['area_code','like','%'.$value['value'].'%'];
                if ($store_id > 0) {
                    $condition[] = ['store_id','=',$store_id];
                }
                $condition1 = $condition;
                if ($shipping_type_id > 0) {
                    $condition[] = ['shipping_type_id','=',$shipping_type_id];
                    $condition1[] = ['shipping_type_id','<>',$shipping_type_id];
                }
                $count1 = $shippingTemplateModel->where($condition1)->count();
                if ($count1 > 0) {
                    unset($city_list[$key]);
                    continue;
                }
                $count = $shippingTemplateModel
                ->where($condition)
                ->count();
                $city_list[$key]['selected'] = false;
                if ($count > 0) {
                    $city_list[$key]['selected'] = true;
                }
            }
            $citys = [];
            foreach ($city_list as $key => $value) {
                $citys[] = $value;
            }
        }

        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = $citys;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 推送记录
     * @method                                      pushMsg
     * @param                                       PushMsgModel $pushMsgModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-03-08Tfalse16:false47:false38+080
     */
    public function pushMsg(PushMsgModel $pushMsgModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page'])?(int)$param['page']:1;
            $limit = isset($param['limit'])?(int)$param['limit']:30;
            $keywords = isset($param['keywords'])?$param['keywords']:'';
            $search_time = isset($param['search_time'])?$param['search_time']:'';
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['pu.user_sn|pu.wechat_openId|pu.android_device_id|pu.ios_device_id|pu.title|pu.content|u.user_name|u.tel','like','%'.$keywords.'%'];
            }
            $resultData = [];
            $resultData['list'] = $pushMsgModel
                              ->alias('pu')
                              ->leftJoin('user u','u.user_sn = pu.user_sn')
                              ->field('pu.`user_sn`,pu.`title`,pu.`content`,pu.`create_time`,pu.`is_wechat`,pu.`is_android`,pu.`is_ios`,u.`user_name`')
                              ->withAttr('is_wechat',function($value,$data){
                                return $value==1?'<span style="color:green;">已送达</span>':'<span style="color:red;">未送达</span>';
                              })
                              ->withAttr('is_android',function($value,$data){
                                return $value==1?'<span style="color:green;">已送达</span>':'<span style="color:red;">未送达</span>';
                              })
                              ->withAttr('is_ios',function($value,$data){
                                return $value==1?'<span style="color:green;">已送达</span>':'<span style="color:red;">未送达</span>';
                              })
                              ->where($condition)
                              ->page($page, $limit)
                              ->order('pu.create_time desc')
                              ->select()
                              ->toArray();
            $resultData['count'] = $pushMsgModel->alias('pu')->leftJoin('user u','u.user_sn = pu.user_sn')->where($condition)->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch('');
    }
}
